<?php
namespace App\Admin\Controllers\Market;
use App\Models\Activity;
use App\Models\ActivityCoupon;
use App\Models\Coupon;
use Dcat\Admin\Controllers\AdminController;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;

class ActivityController extends AdminController
{

    public $title = '活动';

    protected function grid()
    {
        return Grid::make(new Activity(), function (Grid $grid) {

            $grid->model()->with('coupon');

            $grid->column('name', '优惠类型');

            $grid->column('coupon', '优惠券')->display(function ($coupon){
                return implode(',', array_column($coupon, 'name'));
            });

            $grid->status('状态')->switch();


        });
    }



    protected function form()
    {

        return Form::make(new Activity(), function (Form $form){

            $form->text('name', '优惠类型')->required();

            if($form->model()->id) {
                $select_coupon = ActivityCoupon::query()->where('activity_id', $form->model()->id)->get()->toArray();
                $form->model()->coupon = implode(',', array_column($select_coupon, 'coupon_id'));
            }
            $form->multipleSelect('coupon', '优惠券')
                ->options(Coupon::query()->pluck('name', 'id'));
            $form->switch('status', '状态')->default(1);

            $form->saved(function ($form){
                $activity_coupon_model = new ActivityCoupon();
                $activity_coupon_model->setData((int) $form->getKey(), (array) $form->coupon);
            });

        });

    }

}
